package command.server;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.MessageCommunication;
import model.User;
import persistence.UserDAO;
import server.ClientThread;
import server.Server;

public class LoginUserServer implements CommandServer {

    private UserDAO persistenceMechanism;
    private User finalUser;

    public LoginUserServer() {
    }

    public User getFinalUser() {
        return finalUser;
    }

    @Override
    public void execute(ClientThread clientThread) {
        persistenceMechanism = Server.getServerUserDAO();
        try {
            User u = (User) clientThread.getObjectInputStream().readObject();
            finalUser = persistenceMechanism.getUserByEmail(u.getUserEmail());
            if (finalUser != null) {
                if (u.getUserPassword().equals(finalUser.getUserPassword())) {
                    clientThread.getObjectOutputStream().
                            writeObject(new MessageCommunication(true, "El usuario se ha logueado con éxito"));
                    clientThread.getObjectOutputStream().flush();
                    clientThread.getObjectOutputStream().writeObject(finalUser);
                } else {
                    clientThread.getObjectOutputStream().
                            writeObject(new MessageCommunication(false, "La contraseña no es válida"));
                }
                clientThread.getObjectOutputStream().flush();
            } else {
                clientThread.getObjectOutputStream().
                        writeObject(new MessageCommunication(false, "El Usuario no existe"));
                clientThread.getObjectOutputStream().flush();
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(LoginUserServer.class.getName()).log(Level.SEVERE,
                    "Fallo al realizar el login del Usuario", ex);
        }
    }
}
